package cn.hpclub.server.model;

import java.util.List;
import java.util.Map;

import com.jfinal.ext.plugin.tablebind.TableBind;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import cn.hpclub.server.constant.Constant;
import cn.hpclub.server.util.DESAS;
import cn.hpclub.server.util.InterfaceUtil;

/**
 * 实体类 - 账户
 * 
 */
@TableBind(tableName = "sys_user")
public class SysUser extends Model<SysUser>{
    private static final long   serialVersionUID     = -1281976879355944503L;
    public static final SysUser dao                  = new SysUser();

    public static String        ID                   = "id";
    public static String        USER_NAME            = "user_name";
    public static String        PASSWORD             = "password";
    public static String        SALT                 = "salt";
    public static String        REAL_NAME            = "real_name";
    public static String        TELEPHONE            = "telephone";
    public static String        EMAIL                = "email";
    public static String        ORG_ID               = "org_id";

    public static String        IS_ACCOUNTENABLED    = "isAccountEnabled";
    public static String        IS_ACCOUNTEXPIRED    = "isAccountExpired";
    public static String        IS_ACCOUNTLOCKED     = "isAccountLocked";
    public static String        IS_CREDENTIALEXPIRED = "isCredentialsExpired";
    public static String        LOCKEDDATE           = "lockedDate";

    public static String        LOGINDATE            = "loginDate";
    public static String        LOGINFAILCOUNT       = "loginFailureCount";
    public static String        LOGINIP              = "loginIp";
    public static String        IS_DELETED           = "is_deleted";
    public static String        CREATED_BY           = "created_by";
    public static String        CREATED_TIME         = "created_time";
    public static String        LAST_UPDATEED_BY     = "last_updated_by";
    public static String        LAST_UPDATEED_TIME   = "last_updated_time";

    public Page<SysUser> list(int number, int size, Map<String,String> searchInfo){

        String select = "select j.DisplayName as orgName,r.name as roleName,u.* ";
        String sqlExceptSelect = "from sys_user u left join organization j on j.id=u.org_id left join sys_user_role ur on ur.user_id=u.id left join sys_role r on r.id=ur.role_id";
        int orgid = InterfaceUtil.getOrgId();
        Integer level = InterfaceUtil.getRoleLevel();
        Page<SysUser> pager;
        // 角色等级为0的可以查看所有用户
        if(null != level && level.equals(0)){
            sqlExceptSelect += " where 1=1 ";
        } else{
            sqlExceptSelect += " where (u.org_id!=" + orgid + " or u.id=" + InterfaceUtil.getAdminId() + ")";
            sqlExceptSelect += " and j.id in "
                    + InterfaceUtil.getChlidOrgIdSql(InterfaceUtil.getOrgId(), Constant.MAX_ORG_LEVEL, true);
        }
        for(Map.Entry<String, String> item : searchInfo.entrySet()){
            sqlExceptSelect += buildQuery(item);
        }
        // System.out.println("select=" + select);
        // System.out.println("sqlExceptSelect=" + sqlExceptSelect);
        pager = paginate(number, size, select, sqlExceptSelect);
        encryptId(pager);

        return pager;
    }

    private void encryptId(Page<SysUser> pager){
        try{
            DESAS des = new DESAS();
            List<SysUser> list = pager.getList();
            for(int i = 0; i < list.size(); i++){
                SysUser sysUser = list.get(i);
                sysUser.put("id", des.encrypt(sysUser.getInt("id") + ""));
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }

    public Record getUser(int id){
        String sql = "select distinct sys_user.*,organization.DisplayName as orgName,sys_user_role.role_id as roleId,sys_role.name as roleName"
                + " from sys_user,organization,sys_user_role,sys_role"
                + " where sys_user.id=? and organization.id=sys_user.org_id and sys_user_role.user_id=? and sys_role.id=sys_user_role.role_id";
        return Db.findFirst(sql, new Object[] { id, id });
    }

    public SysUser findUserById(String id){
        int orgId = InterfaceUtil.getOrgId();
        String chlidOrgIdSql = InterfaceUtil.getChlidOrgIdSql(orgId, Constant.MAX_ORG_LEVEL, true);
        String sql = "SELECT * FROM sys_user WHERE id=? AND org_id IN " + chlidOrgIdSql;
        System.out.println("sql:" + sql);
        return findFirst(sql, id);
    }

    private String buildQuery(Map.Entry<String, String> item){
        if("org_id".equalsIgnoreCase(item.getKey())){
            return " and u.org_id in "
                    + InterfaceUtil.getChlidOrgIdSql(Integer.parseInt(item.getValue()), Constant.MAX_ORG_LEVEL, true);
        }
        if("roleName".equalsIgnoreCase(item.getKey())){
            return " and r.name like '%" + item.getValue() + "%' ";
        }
        if("name".equalsIgnoreCase(item.getKey())){
            return  " and (u.real_name like '%" + item.getValue() + "%' or u.user_name like '%" + item.getValue()+ "%')";
        }
        return " and a." + item.getKey() + " = '" + item.getValue() + "'";
    }
}
